package nc.bs.common.util;

import nc.bs.dao.BaseDAO;
import nc.bs.dao.DAOException;
import nc.bs.pub.util.BaseDaoUtil;
import nc.jdbc.framework.SQLParameter;
import nc.jdbc.framework.processor.BeanListProcessor;
import nc.jdbc.framework.processor.ResultSetProcessor;
import nc.vo.pubapp.pattern.exception.ExceptionUtils;

import java.util.List;

/**
 * @author duanyp1
 * @date 2024/3/15 9:59
 */
public class DaoUtil {

    private static BaseDAO dao;

    private static BaseDAO getDao() {
        return dao == null ? dao = BaseDaoUtil.getInstance() : dao;
    }

    public static <T> List<T> executeQueryList(String sql, Class<T> clazz) {
        return executeQueryList(sql, null, clazz);
    }

    public static void e(){

    }

    public static <T> List<T> executeQueryList(String sql, SQLParameter parameter, Class<T> clazz) {
        return (List<T>) executeQuery(sql, parameter, new BeanListProcessor(clazz));
    }

    public static <T> T retrieveByPK(Class<T> clazz, String pk) {
        try {
            return (T) getDao().retrieveByPK(clazz, pk);
        } catch (DAOException e) {
            ExceptionUtils.wrappException(e);
        }
        return null;
    }

    public static Object executeQuery(String sql, ResultSetProcessor processor) {
        return executeQuery(sql, null, processor);
    }

    public static Object executeQuery(String sql, SQLParameter parameter, ResultSetProcessor processor) {
        try {
            return parameter == null ? getDao().executeQuery(sql, processor) : getDao().executeQuery(sql, parameter, processor);
        } catch (DAOException e) {
            ExceptionUtils.wrappException(e);
        }
        return null;
    }

    public static int executeUpdate(String sql) {
        return executeUpdate(sql,null);
    }

    public static int executeUpdate(String sql, SQLParameter parameter) {
        int result = 0;
        try {
            if(parameter == null){
                result = getDao().executeUpdate(sql);
            }else {
                result = getDao().executeUpdate(sql, parameter);
            }
        } catch (DAOException e) {
            ExceptionUtils.wrappException(e);
        }
        return result;
    }


    public static boolean isTableExist(String tableName) {
        try {
            return getDao().isTableExisted(tableName);
        } catch (DAOException e) {
            ExceptionUtils.wrappException(e);
        }
        return false;
    }

}
